package com.universest.swordholder.viewmodel.passage_editor

import androidx.compose.ui.text.input.TextFieldValue
import java.util.LinkedList

class TextEditHistory(textFieldValue: TextFieldValue?) {

    private val _history = LinkedList<TextFieldValue>()

    private val maxHistoryCount = 30

    init {
        textFieldValue?.let {
            _history.addLast(it)
        }
    }

    private var _currentIndex = 0;
    fun hasHistory(): Boolean =
        _history.isNotEmpty() && _currentIndex >= 1

    fun canRedo(): Boolean =
        _currentIndex < _history.size - 1

    fun resetHistory(textFieldValue: TextFieldValue){
        _history.clear()
        _history.add(textFieldValue)
        _currentIndex = 0
    }

    /**
     * 撤销上一次的操作，将文本恢复至上一历史节点。
     * 若无更早的历史记录则不做处理。
     */
    fun undo(): TextFieldValue?{
        if(!hasHistory())return null
        _currentIndex--
        val historyValue = _history[_currentIndex]
        return historyValue
    }

    fun redo(): TextFieldValue?{
        if(!canRedo())return null
        _currentIndex++
        val historyValue = _history[_currentIndex]
        return historyValue
    }

    fun addHistory(newValue: TextFieldValue){
        // 清理当前位置之后的所有历史记录
        if (_history.isNotEmpty() && _currentIndex < _history.size-1) {
            _history.subList(_currentIndex+1, _history.size).clear()
        }
        _history.add(newValue)
        // 控制历史记录的最大长度
        if (_history.size > maxHistoryCount) {
            _history.removeFirst()
        }
        _currentIndex = _history.size-1
    }
}